package main

import (
	"context"
	"strconv"
	"strings"
	"time"

	"gitee.com/hacker61/go-binance/v2/futures"
)

type FundingRate struct {
	CreateSymbols      map[string]struct{}
	CloseSymbols       map[string]struct{}
	SymbolFundingRates map[string]float64
	getTicker          *time.Ticker
	futuresClient      *futures.Client
	fundingRateOpt     *FundingRateOPT
}

func (fr *FundingRate) getSymbolsFundingRate() {
	premiumIndexService := fr.futuresClient.NewPremiumIndexService()
	indexes, err := premiumIndexService.Do(context.Background())
	if err != nil {
		Error.Println(err)
		return
	}
	//Info.Println(indexes)
	fr.CreateSymbols = make(map[string]struct{})
	for _, index := range indexes {
		if strings.HasSuffix(index.Symbol, "USDT") {
			lastFundingRate, _ := strconv.ParseFloat(index.LastFundingRate, 64)
			fr.SymbolFundingRates[index.Symbol] = lastFundingRate
			if lastFundingRate > fr.fundingRateOpt.CreateFundingRate {
				fr.CreateSymbols[index.Symbol] = struct{}{}
			} else if lastFundingRate < fr.fundingRateOpt.CloseFundingRate {
				fr.CloseSymbols[index.Symbol] = struct{}{}
			}
		}
	}
	Info.Println(fr.CreateSymbols)
}

func NewFundingRate(fclient *futures.Client, fro *FundingRateOPT) *FundingRate {
	pfr := new(FundingRate)
	pfr.CreateSymbols = make(map[string]struct{})
	pfr.CloseSymbols = make(map[string]struct{})
	pfr.SymbolFundingRates = make(map[string]float64)
	pfr.getTicker = time.NewTicker(time.Duration(fro.GetFundingRateDuration) * time.Second)
	pfr.futuresClient = fclient
	pfr.fundingRateOpt = fro

	pfr.getSymbolsFundingRate()

	//go func() {
	//	for {
	//		<-pfr.getTicker.C
	//		pfr.getSymbolsFundingRate()
	//	}
	//}()

	return pfr
}
